#include "MuxReader.h"

#define MUX_FRAME_START 0xBF

MuxReader::MuxReader(Reader* reader)
{
	_reader = reader;
}


MuxReader::~MuxReader(void)
{
	_reader = 0;
}


__int16 MuxReader::ReadFrame(char* buffer, __int16 buffer_length)
{
	while(_reader->Read() != MUX_FRAME_START);
	char link = _reader->Read();
	__int16 frame_length = (_reader->Read() & 0x03 ); // Flags ignorieren
	frame_length <<= 8;
	frame_length &= _reader->Read();

	char* p_buffer = buffer;	
	for(__int16 i=0; i<frame_length; i++)
	{
		if(i<buffer_length) *p_buffer++ = _reader->Read();		
		else _reader->Read();
	}
	char n_link = _reader->Read();

	if ((n_link==link^0xFF) && (frame_length<=buffer_length))
	{
		return frame_length;
	}
	return -1;
}
